package cn.edu.baiyunu.myapplication.ui.screens.profile

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Category
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import cn.edu.baiyunu.myapplication.data.model.Category
import cn.edu.baiyunu.myapplication.ui.components.GlassmorphismCard
import cn.edu.baiyunu.myapplication.ui.components.GradientBackground
import cn.edu.baiyunu.myapplication.ui.screens.profile.viewmodel.ProfileViewModel

// 预定义图标列表
val availableIcons = listOf(
    "restaurant" to Icons.Filled.Category,
    "shopping_cart" to Icons.Filled.Category,
    "directions_bus" to Icons.Filled.Category,
    "home" to Icons.Filled.Category,
    "sports_esports" to Icons.Filled.Category,
    "local_hospital" to Icons.Filled.Category,
    "school" to Icons.Filled.Category,
    "work" to Icons.Filled.Category,
    "card_giftcard" to Icons.Filled.Category,
    "savings" to Icons.Filled.Category,
    "schedule" to Icons.Filled.Category,
    "pets" to Icons.Filled.Category,
    "fitness_center" to Icons.Filled.Category,
    "flight" to Icons.Filled.Category,
    "phone" to Icons.Filled.Category,
    "movie" to Icons.Filled.Category,
    "business" to Icons.Filled.Category,
    "laptop" to Icons.Filled.Category,
    "local_cafe" to Icons.Filled.Category,
    "wine_bar" to Icons.Filled.Category
)

/**
 * 分类管理页面
 */
@Composable
fun CategoryManagerScreen(
    onBackClick: () -> Unit,
    viewModel: ProfileViewModel = hiltViewModel()
) {
    val uiState by viewModel.profileUiState.collectAsStateWithLifecycle()
    var selectedTabIndex by remember { mutableStateOf(0) }
    
    // 对话框状态
    var showAddCategoryDialog by remember { mutableStateOf(false) }
    var showDeleteConfirmDialog by remember { mutableStateOf(false) }
    var editingCategory by remember { mutableStateOf<Category?>(null) }
    var deletingCategory by remember { mutableStateOf<Category?>(null) }
    
    GradientBackground {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .systemBarsPadding()
        ) {
            // 顶部栏
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 返回按钮
                Box(
                    modifier = Modifier
                        .size(40.dp)
                        .clip(CircleShape)
                        .background(Color.White.copy(alpha = 0.1f))
                        .clickable { onBackClick() },
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = Icons.Filled.ArrowBack,
                        contentDescription = "返回",
                        tint = Color.White,
                        modifier = Modifier.size(24.dp)
                    )
                }
                
                // 标题
                Text(
                    text = "分类管理",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White,
                    modifier = Modifier
                        .weight(1f)
                        .padding(horizontal = 16.dp)
                )
                
                // 添加按钮
                Box(
                    modifier = Modifier
                        .size(40.dp)
                        .clip(CircleShape)
                        .background(Color.White.copy(alpha = 0.1f))
                        .clickable { 
                            editingCategory = null
                            showAddCategoryDialog = true 
                        },
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = Icons.Filled.Add,
                        contentDescription = "添加分类",
                        tint = Color.White,
                        modifier = Modifier.size(24.dp)
                    )
                }
            }
            
            // 选项卡
            GlassmorphismCard(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp)
                    .clip(RoundedCornerShape(15.dp))
            ) {
                TabRow(
                    selectedTabIndex = selectedTabIndex,
                    containerColor = Color.Transparent,
                    contentColor = Color.White,
                    indicator = { /* 不显示默认指示器 */ }
                ) {
                    // 支出选项卡
                    Tab(
                        selected = selectedTabIndex == 0,
                        onClick = { selectedTabIndex = 0 },
                        modifier = Modifier
                            .background(
                                if (selectedTabIndex == 0) Color.White.copy(alpha = 0.2f)
                                else Color.Transparent
                            )
                    ) {
                        Text(
                            text = "支出分类",
                            modifier = Modifier.padding(vertical = 15.dp),
                            color = Color.White
                        )
                    }
                    
                    // 收入选项卡
                    Tab(
                        selected = selectedTabIndex == 1,
                        onClick = { selectedTabIndex = 1 },
                        modifier = Modifier
                            .background(
                                if (selectedTabIndex == 1) Color.White.copy(alpha = 0.2f)
                                else Color.Transparent
                            )
                    ) {
                        Text(
                            text = "收入分类",
                            modifier = Modifier.padding(vertical = 15.dp),
                            color = Color.White
                        )
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(20.dp))
            
            // 分类列表
            GlassmorphismCard(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
                    .padding(horizontal = 20.dp)
                    .clip(RoundedCornerShape(15.dp))
            ) {
                LazyColumn(
                    modifier = Modifier.fillMaxSize()
                ) {
                    val categories = if (selectedTabIndex == 0) {
                        uiState.expenseCategories
                    } else {
                        uiState.incomeCategories
                    }
                    
                    items(categories) { category ->
                        CategoryItem(
                            category = category,
                            onEditClick = {
                                editingCategory = category
                                showAddCategoryDialog = true
                            },
                            onDeleteClick = {
                                deletingCategory = category
                                showDeleteConfirmDialog = true
                            }
                        )
                    }
                }
            }
        }
    }
    
    // 添加/编辑分类对话框
    if (showAddCategoryDialog) {
        CategoryDialog(
            category = editingCategory,
            onDismiss = { showAddCategoryDialog = false },
            onSave = { name, icon -> 
                if (editingCategory != null) {
                    viewModel.updateCategory(editingCategory!!.id, name, icon)
                } else {
                    val type = if (selectedTabIndex == 0) "expense" else "income"
                    viewModel.addCategory(name, icon, type)
                }
                showAddCategoryDialog = false
            }
        )
    }
    
    // 删除确认对话框
    if (showDeleteConfirmDialog && deletingCategory != null) {
        AlertDialog(
            containerColor = Color(0xFF1E1E1E),
            titleContentColor = Color.White,
            textContentColor = Color.White,
            onDismissRequest = { showDeleteConfirmDialog = false },
            title = { Text("删除分类") },
            text = { Text("确定要删除\"${deletingCategory?.name}\"分类吗？") },
            confirmButton = {
                TextButton(
                    onClick = {
                        viewModel.deleteCategory(deletingCategory!!.id)
                        showDeleteConfirmDialog = false
                        deletingCategory = null
                    }
                ) {
                    Text("删除", color = Color(0xFFFF5E62))
                }
            },
            dismissButton = {
                TextButton(
                    onClick = { showDeleteConfirmDialog = false }
                ) {
                    Text("取消", color = Color.White)
                }
            }
        )
    }
}

/**
 * 分类项目
 */
@Composable
private fun CategoryItem(
    category: Category,
    onEditClick: () -> Unit,
    onDeleteClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(15.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 图标
        Box(
            modifier = Modifier
                .size(40.dp)
                .clip(RoundedCornerShape(10.dp))
                .background(Color.White.copy(alpha = 0.1f)),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                imageVector = Icons.Filled.Category, // 使用默认图标
                contentDescription = null,
                tint = Color.White,
                modifier = Modifier.size(24.dp)
            )
        }
        
        // 名称
        Text(
            text = category.name,
            fontSize = 16.sp,
            color = Color.White,
            modifier = Modifier
                .weight(1f)
                .padding(start = 15.dp)
        )
        
        // 编辑按钮
        IconButton(
            onClick = onEditClick,
            modifier = Modifier
                .size(36.dp)
                .clip(CircleShape)
                .background(Color.White.copy(alpha = 0.1f))
        ) {
            Icon(
                imageVector = Icons.Filled.Edit,
                contentDescription = "编辑",
                tint = Color.White,
                modifier = Modifier.size(20.dp)
            )
        }
        
        Spacer(modifier = Modifier.size(10.dp))
        
        // 删除按钮
        IconButton(
            onClick = onDeleteClick,
            modifier = Modifier
                .size(36.dp)
                .clip(CircleShape)
                .background(Color(0xFFFF5E62).copy(alpha = 0.2f))
        ) {
            Icon(
                imageVector = Icons.Filled.Delete,
                contentDescription = "删除",
                tint = Color.White,
                modifier = Modifier.size(20.dp)
            )
        }
    }
    
    // 分隔线
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(1.dp)
            .padding(horizontal = 15.dp)
            .background(Color.White.copy(alpha = 0.1f))
    )
}

/**
 * 添加/编辑分类对话框
 */
@Composable
private fun CategoryDialog(
    category: Category? = null,
    onDismiss: () -> Unit,
    onSave: (name: String, icon: String) -> Unit
) {
    var categoryName by remember { mutableStateOf(category?.name ?: "") }
    var selectedIcon by remember { mutableStateOf(category?.icon ?: availableIcons[0].first) }
    
    Dialog(onDismissRequest = onDismiss) {
        Box(
            modifier = Modifier
                .clip(RoundedCornerShape(15.dp))
                .background(Color(0xFF1E1E1E))
                .border(1.dp, Color.White.copy(alpha = 0.1f), RoundedCornerShape(15.dp))
                .padding(25.dp)
        ) {
            Column {
                // 标题
                Text(
                    text = if (category == null) "添加分类" else "编辑分类",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White,
                    modifier = Modifier.align(Alignment.CenterHorizontally)
                )
                
                Spacer(modifier = Modifier.height(20.dp))
                
                // 分类名称输入框
                OutlinedTextField(
                    value = categoryName,
                    onValueChange = { categoryName = it },
                    label = { Text("分类名称") },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(),
                    colors = TextFieldDefaults.colors(
                        unfocusedContainerColor = Color.White.copy(alpha = 0.1f),
                        focusedContainerColor = Color.White.copy(alpha = 0.15f),
                        unfocusedTextColor = Color.White,
                        focusedTextColor = Color.White,
                        unfocusedLabelColor = Color.White.copy(alpha = 0.7f),
                        focusedLabelColor = Color.White,
                        unfocusedIndicatorColor = Color.Transparent,
                        focusedIndicatorColor = Color.White
                    )
                )
                
                Spacer(modifier = Modifier.height(20.dp))
                
                // 图标选择
                Text(
                    text = "选择图标",
                    fontSize = 14.sp,
                    color = Color.White.copy(alpha = 0.8f)
                )
                
                Spacer(modifier = Modifier.height(10.dp))
                
                // 图标网格
                LazyVerticalGrid(
                    columns = GridCells.Fixed(5),
                    horizontalArrangement = Arrangement.spacedBy(10.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp),
                    modifier = Modifier.height(200.dp)
                ) {
                    items(availableIcons) { (iconName, iconVector) ->
                        IconOption(
                            iconVector = iconVector,
                            isSelected = selectedIcon == iconName,
                            onClick = { selectedIcon = iconName }
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(20.dp))
                
                // 按钮
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 取消按钮
                    Button(
                        onClick = onDismiss,
                        modifier = Modifier.weight(1f),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color.White.copy(alpha = 0.1f),
                            contentColor = Color.White
                        )
                    ) {
                        Text("取消")
                    }
                    
                    // 保存按钮
                    Button(
                        onClick = { 
                            if (categoryName.isNotBlank()) {
                                onSave(categoryName, selectedIcon)
                            }
                        },
                        modifier = Modifier.weight(1f),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF26DE81).copy(alpha = 0.2f),
                            contentColor = Color.White
                        ),
                        enabled = categoryName.isNotBlank()
                    ) {
                        Text("保存")
                    }
                }
            }
        }
    }
}

/**
 * 图标选项
 */
@Composable
private fun IconOption(
    iconVector: ImageVector,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Box(
        modifier = Modifier
            .size(40.dp)
            .clip(CircleShape)
            .background(
                if (isSelected) Color.White.copy(alpha = 0.3f)
                else Color.White.copy(alpha = 0.1f)
            )
            .border(
                width = if (isSelected) 2.dp else 0.dp,
                color = if (isSelected) Color.White else Color.Transparent,
                shape = CircleShape
            )
            .clickable(onClick = onClick),
        contentAlignment = Alignment.Center
    ) {
        Icon(
            imageVector = iconVector,
            contentDescription = null,
            tint = Color.White,
            modifier = Modifier.size(24.dp)
        )
        
        if (isSelected) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(2.dp),
                contentAlignment = Alignment.BottomEnd
            ) {
                Box(
                    modifier = Modifier
                        .size(14.dp)
                        .clip(CircleShape)
                        .background(Color(0xFF26DE81)),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = Icons.Filled.Check,
                        contentDescription = null,
                        tint = Color.White,
                        modifier = Modifier.size(10.dp)
                    )
                }
            }
        }
    }
} 